
import 'buy_record_model.dart';
import 'sell_record_model.dart';

class StockPositionModel {
  final String symbol;
  final String name;
  final List<BuyRecordModel> buyRecords;
  final List<SellRecordModel> sellRecords;
  final double currentPrice;
  final double changePercent;

  StockPositionModel({
    required this.symbol,
    required this.name,
    required this.buyRecords,
    required this.sellRecords,
    this.currentPrice = 0.0,
    this.changePercent = 0.0,
  });

  // 计算总持仓数量
  int get totalQuantity {
    return buyRecords.fold(0, (sum, record) => sum + record.remainingQuantity);
  }

  // 计算总买入金额
  double get totalInvestment {
    return buyRecords.fold(0.0, (sum, record) => sum + (record.buyPrice * record.remainingQuantity));
  }

  // 计算平均成本
  double get averageCost {
    return totalQuantity > 0 ? totalInvestment / totalQuantity : 0.0;
  }

  // 计算浮动盈亏
  double get floatingProfitLoss {
    return (currentPrice - averageCost) * totalQuantity;
  }

  // 计算浮动盈亏百分比
  double get floatingProfitLossPercent {
    return averageCost > 0 ? ((currentPrice - averageCost) / averageCost) * 100 : 0.0;
  }

  // 计算实际盈亏（已卖出部分）
  double get realizedProfitLoss {
    return sellRecords.fold(0.0, (sum, record) {
      final buyRecord = buyRecords.firstWhere((b) => b.id == record.buyRecordId);
      return sum + ((record.sellPrice - buyRecord.buyPrice) * record.sellQuantity);
    });
  }
}